package quiz;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ResultServlet
 */
@WebServlet("/Result")
public class ResultServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ResultServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		long timeTakenMillis = System.currentTimeMillis() - (Long)request.getSession().getAttribute("time");
		String time = String.format("%d min, %d sec", 
			    TimeUnit.MILLISECONDS.toMinutes(timeTakenMillis),
			    TimeUnit.MILLISECONDS.toSeconds(timeTakenMillis) - 
			    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeTakenMillis))
		); //stolen from StackOverflow
		request.getSession().setAttribute("time", time); //reuse time variable
		
		Account currentAcct = (Account) request.getSession().getAttribute("account");
		int acctID;
		acctID = (currentAcct == null) ? -1 : currentAcct.getID(); //Anonymous or actual user
		Quiz currentQuiz =  (Quiz)request.getSession().getAttribute("quiz");
		int score = (Integer) request.getSession().getAttribute("runningScore");
		boolean practiceMode = (Boolean) request.getSession().getAttribute("practiceMode");
		
		Result thisResult = new Result(acctID, currentQuiz.getID(), score, (int)timeTakenMillis, practiceMode);
		DataBase db = (DataBase) request.getServletContext().getAttribute("db");
		
		/*if (practiceMode){
			//check to see if it's the first practice result for this user
			ArrayList<Result> userResults = db.getRecentResultsForUser(acctID, Integer.MAX_VALUE);
			boolean thisIsFirstPracticeResult = true;
			for (int i = 0; i < userResults.size(); i++){
				if (userResults.get(i).getScore() < 0) thisIsFirstPracticeResult = false;
			}
			
			//if so, give them the achievement for PRACTICE MAKES PERFECT
			if (thisIsFirstPracticeResult){
				Achievement a = new Achievement(acctID, Achievement.PRACTICE_MAKES_PERFECT);
				db.storeAchievement(a);
				ArrayList<Achievement> achievementsEarned = new ArrayList<Achievement>();
				achievementsEarned.add(a);
				request.setAttribute("achievementEarned", achievementsEarned);
			}
			
			RequestDispatcher dpatch = request.getRequestDispatcher("quiz-completed.jsp");
			dpatch.forward(request, response);
			return;
		}
		/*
		//if execution gets to this point, it's not practice mode
		//that means we check for additional achievements and then store the result
		
		//check if 10th quiz taken for this user
		ArrayList<Result> allResultsForUser = db.getRecentResultsForUser(acctID, Integer.MAX_VALUE);
		if (allResultsForUser.size() == 10){
			Achievement a = new Achievement(acctID, Achievement.QUIZ_MACHINE);
			db.storeAchievement(a);
		}
		
		//check if this is the highest score for this particular quiz
		ArrayList<Result> topScoresForQuiz = db.getTopQuizResults(currentQuiz.getID(), Integer.MAX_VALUE);
		boolean thisScoreIsHighest = true;
		for (int i = 0; i < topScoresForQuiz.size(); i++){
			if (topScoresForQuiz.get(i).getScore() > score) thisScoreIsHighest = false;
		}
		if (thisScoreIsHighest){
			Achievement a = new Achievement(acctID, Achievement.I_AM_THE_GREATEST);
			db.storeAchievement(a);
		}*/
		
		db.storeResult(thisResult);
		ArrayList<Achievement> a = null;
		if (currentAcct != null) 
			 a = currentAcct.checkAchievements();
		
		request.setAttribute("achievementEarned", a);
		request.setAttribute("runningScore", request.getSession().getAttribute("runningScore"));
		request.setAttribute("quiz", request.getSession().getAttribute("quiz"));
		request.setAttribute("answers", request.getSession().getAttribute("answers"));
		request.setAttribute("practiceMode", request.getSession().getAttribute("practiceMode"));
		request.setAttribute("time", request.getSession().getAttribute("time"));
		
		//set all things to null
		request.getSession().setAttribute("quiz", null);		
		request.getSession().setAttribute("answers", null);
		request.getSession().setAttribute("runningScore", null);
		request.getSession().setAttribute("runningPossibleScore", null);
		request.getSession().setAttribute("time",null);
		request.getSession().setAttribute("practiceMode", null);
		request.getSession().setAttribute("questionsLeft", null);
		
		RequestDispatcher dpatch = request.getRequestDispatcher("quiz-completed.jsp");
		dpatch.forward(request, response);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}

}
